var express = require('express');
var router = express.Router();
const uuid = require('uuid');
const customer = require("../sql/Customer");
const order = require("../sql/Order");

router.get('/', function(req, res, next) {
  customer.find().then(customerData=>{
    const { employeesName } = req.session.userData;
    res.render('customer', { employeesName, index:5, customerData:customerData });
  })
});

// 添加客户
router.post('/add', function(req, res, next) {
  const {cName} = req.body;
  if(cName){
    customer.insertMany({
      cId: 'customer-'+uuid.v1(),
      cName
    }).then(()=>{
      res.redirect('/customer');
    }).catch(code=>{
      res.redirect('/customer');
      console.error(code);
    })
  }else{
    res.redirect('/customer');
  }
});

// 删除客户
router.get('/delete', function(req, res, next) {
  const {cId} = req.query;

  order.find({ CustomerName: cId }).then(orderData=>{
    if(orderData.length > 0){
      res.send({ msg: '该客户已存在以下关联订单，不允许删除！', data: orderData.map(v=>v.AccountingNo) });
    }else{
      customer.deleteOne({cId}).then(()=>{
        res.redirect('/customer');
      }).catch(code=>{
        res.redirect('/customer');
        console.error(code);
      })
    }
  })

});

// 修改客户
router.post('/set', function(req, res, next) {
  const {cId, cName} = req.body;
  customer.updateOne({cId}, {cName}).then(()=>{
    res.redirect('/customer');
  }).catch(code=>{
    res.redirect('/customer');
    console.error(code);
  })
});


module.exports = router;
